package com.kele.es_project.utils;

import com.kele.es_project.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @Version 2019
 * @Author:kele
 * @Date:2021/4/6
 * @Content:
 * @Description：
 */
@Component
public class HtmlParseUtils {

//    public static void main(String[] args) throws Exception {
//
//        new HtmlParseUtils().pareJD("vue").forEach(System.out::println);
//    }

    public List<Content> pareJD(String keyword) throws Exception{
        //https://search.jd.com/Search?keyword=java&enc=utf-8&wq=java&pvid=6af8a61dff474a65957b65d9d27b9de5
        String url="https://search.jd.com/Search?keyword="+keyword;
        //解析网页
        Document document = Jsoup.parse(new URL(url), 3000);
        Element element = document.getElementById("J_goodsList");
        //System.out.println(element);

        Elements li = element.getElementsByTag("li");

        List contentList=new ArrayList<Content>();

        for (Element el:li
        ) {
            String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();

            Content content=new Content();
            content.setImg(img);
            content.setTitle(title);
            content.setPrice(price);
            contentList.add(content);
        }

        return contentList;
    }
}
